package com.xueyuan.wata.daph.tools.jsonloader

import java.sql.{Connection, DriverManager}

class MySQLJsonLoader(config: Map[String, String]) extends JsonLoader {
  override def load(path: String): String = {
    val tableName = config("tableName")
    val id = config("id")

    val json = conn.createStatement.executeQuery(s"SELECT $path FROM $tableName WHERE $id").getString(1)
    json
  }

  override def loadAll(jsonPath: DJson): DJson = {
    val tableName = config("tableName")
    val id = config("id")
    val path = s"${jsonPath.job},${jsonPath.computer},${jsonPath.storage},${jsonPath.executor}"

    val query = conn.createStatement.executeQuery(s"SELECT $path FROM $tableName WHERE $id")
    val job = query.getString(1)
    val computer = query.getString(2)
    val storage = query.getString(3)
    val executor = query.getString(4)

    DJson(job, computer, storage, executor)
  }

  private def conn: Connection = {
    val url = config("url")
    val user = config("user")
    val password = config("password")

    val conn = DriverManager.getConnection(url, user, password)
    conn
  }
}
